import React, { useEffect, useState } from "react";
import { Dropdown, MenuProps } from "antd";
import { NodeType, NODE_TYPE_LIST, NODE_TYPE_LOGO } from "./types";
import { Cell } from "@antv/x6";
import { getInjector, getNodeTypes } from "hqhui";

/**
 * @file NodeTypeSelector.tsx
 * @description 节点类型选择下拉菜单组件，用于选择并创建新的流程图节点
 */

/**
 * 节点类型选择器属性接口
 */
interface NodeTypeSelectorProps {
  visible: boolean; // 是否显示选择器
  position: { x: number; y: number }; // 选择器的位置坐标
  context: {
    source: Cell | null; // 源节点
    target: Cell | null; // 目标节点
    edge: Cell | null; // 边
  };
  onNodeTypeSelect: (nodeType: NodeType) => void; // 节点类型选择回调
  onClose: () => void; // 关闭选择器回调
}

/**
 * 节点类型选择下拉菜单组件
 * 提供节点类型选择功能，支持动态加载节点类型
 */
const NodeTypeSelector: React.FC<NodeTypeSelectorProps> = ({
  visible,
  position,
  context,
  onNodeTypeSelect,
  onClose,
}) => {
  const [nodeTypes, setNodeTypes] = useState(getNodeTypes());
  
  /**
   * 监听节点元数据和类型变化
   * 使用注入器订阅动态节点类型的更新
   */
  useEffect(() => {
    const updateData = () => {
      setNodeTypes(getNodeTypes());
    };

    // 初始化数据
    updateData();
    
    // 使用订阅机制监听变化
    const unsubscribe = getInjector().subscribe(updateData);
    return () => unsubscribe();
  }, []);
  
  /**
   * 生成菜单项
   * 组合本地节点类型和动态节点类型
   * @returns 菜单项数组
   */
  const getMenuItems = (): MenuProps["items"] => {
    const arr = [...NODE_TYPE_LIST, ...nodeTypes];
    return arr.map((item) => ({
      key: item.value,
      icon: (
        <img
          src={
            NODE_TYPE_LOGO[item.value as NodeType] ||
            "https://mdn.alipayobjects.com/huamei_f4t1bn/afts/img/A*EHqyQoDeBvIAAAAAAAAAAAAADtOHAQ/original"
          }
          alt={item.label}
          style={{ width: 16, height: 16, marginRight: 8 }}
        />
      ),
      label: item.label,
      onClick: () => onNodeTypeSelect(item.value as NodeType),
    }));
  };

  if (!visible) {
    return null;
  }

  return (
    <Dropdown
      menu={{
        items: getMenuItems(),
      }}
      open={visible}
      onOpenChange={onClose}
      trigger={["contextMenu"]}
      popupRender={(menu) => (
        <div
          style={{
            zIndex: 1000,
            position: "fixed",
            left: `${position.x}px`,
            top: `${position.y}px`,
          }}
        >
          {menu}
        </div>
      )}
    >
      <div style={{ display: "none" }} />
    </Dropdown>
  );
};

export default NodeTypeSelector;